package com.nineclock.auth.aop;

import com.nineclock.auth.entity.IntegrationAuthenticationEntity;
import com.nineclock.auth.threadlocal.IntegrationAuthenticationHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Component
@Slf4j
@Aspect //配置切面
public class AuthTokenAspect {
    //从容器注入 请求对象
    @Autowired
    HttpServletRequest request;

    @Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
    public Object around(ProceedingJoinPoint joinPoint){
        try {
            //获取 认证类型
            String authType = request.getParameter("auth_type");
            //获取 所有参数的 map集合
            Map<String, String[]> parameterMap = request.getParameterMap();

            IntegrationAuthenticationEntity entity = new IntegrationAuthenticationEntity();
            entity.setAuthType(authType); //赋值  认证类型
            entity.setAuthParameters(parameterMap); //赋值 其他参数
            //存储到 当前线程
            IntegrationAuthenticationHolder.set(entity);
            //调用原始方法
            //resultObj 是原始方法的返回值
            Object resultObj = joinPoint.proceed();

            //环绕后 增强

            return resultObj;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }
}